#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

async function main() {

  function getPagesDirNames(pagesDir) {
    return fs.readdirSync(pagesDir).filter(file => fs.statSync(path.join(pagesDir, file)).isDirectory());
  }

  function removeComments(str) {
    return str.replace(/\/\/.*$/gm, '');
  }

  async function loadPagesJson(pagesDir, ignoreFile) {
    let subDirs = getPagesDirNames(pagesDir);

    const result = JSON.parse(removeComments(await fs.promises.readFile(path.resolve(__dirname, 'example.json'), 'utf-8')));

    if (fs.existsSync(ignoreFile)) {
      const ignoreList = (await fs.promises.readFile(ignoreFile, 'utf-8')).split(/\r?\n/);
      subDirs = subDirs.filter(subDir => ignoreList.indexOf(subDir) === -1);
    }

    await Promise.all(subDirs.map(async subDir => {
      const pagesJsonPath = path.join(pagesDir, subDir, 'pages.json');
      if (fs.existsSync(pagesJsonPath)) {
        const pagesData = JSON.parse(removeComments(await fs.promises.readFile(pagesJsonPath, 'utf-8')));
        result.pages = Array.from(new Set(result.pages.concat(pagesData.pages).map(JSON.stringify)), JSON.parse);
      }
    }));

    return result;
  }

  const pagesDir = path.join(__dirname, '../src', 'pages');
  const ignoreFile = path.resolve(__dirname, '..', '.pagesIgnore');
  const combinedJson = await loadPagesJson(pagesDir, ignoreFile);
  const outputPath = path.resolve(__dirname, '../src', 'pages.json');
  await fs.promises.writeFile(outputPath, JSON.stringify(combinedJson, null, 2));
}

console.log('----------重要提示^-^-----------------------------------------------------------------------')
console.log('                                                                                            ')
console.log('管e通5.0不需要按业务分包发布了，所有路由配置在创建页面时需要全部添加到pages.json中并提交git。')
console.log('                                                                                            ')
console.log('----------注意注意^-^-----------------------------------------------------------------------')
//main().catch(err => console.error(err));